<template>
    <!--
  <el-dialog 
    :model-value="dialogVisible" 
    width="80%" 
    max-width="600px"
    class="order-result-dialog" 
    @close="handleClose" 
    :close-on-click-modal="false"
  >
  -->
    <el-dialog :model-value="dialogVisible" width="600px" max-width="600px" class="order-result-dialog"
        @close="handleClose" :close-on-click-modal="false">
        <!-- Custom header -->
        <template #header="{ titleId, titleClass }">
            <div class="dialog-header">
                <span :id="titleId" :class="titleClass">开单成功</span>
            </div>
        </template>

        <!-- Main Content -->
        <div class="dialog-content">
            <!-- Order Basic Info -->
            <div class="basic-info-container">
                <div class="section-header">
                    <span class="order-type">{{ orderResult?.docType?.name }}</span>
                    <span v-if="isValidOrder" class="detail-link" @click="showDetail">
                        详情 >
                    </span>
                </div>

                <p class="order-title">{{ orderResult?.title }}</p>

                <!-- Quantity Display -->
                <div v-if="(orderResult.commodityCount || orderResult.fundCount) &&
                    orderResult.docType.code !== DocType.PDD.code &&
                    orderResult.docType.code !== DocType.ASSEMBLER.code" class="quantity-row">
                    <span v-if="orderResult.commodityCount" class="quantity-item">
                        商品数量: {{ formatCount(orderResult.commodityCount.value) }}
                    </span>
                    <span v-if="orderResult.fundCount" class="quantity-item">
                        金额: <span :style="{ color: AppTheme.foundStringColor }">{{
                            formatPrice(orderResult.fundCount.value)
                            }}</span>
                    </span>
                </div>

                <!-- Inventory Sheet Display -->
                <div v-if="(orderResult.commodityCount || orderResult.commodityCount2) &&
                    orderResult.docType.code === DocType.PDD.code" class="quantity-row">
                    <span v-if="orderResult.commodityCount" class="quantity-item">
                        盘盈: {{ formatCount(orderResult.commodityCount.value) }}
                    </span>
                    <span v-if="orderResult.commodityCount2" class="quantity-item">
                        盘亏: {{ formatCount(orderResult.commodityCount2.value) }}
                    </span>
                </div>

                <!-- Assembler Display -->
                <div v-if="(orderResult.comcommodityCount || orderResult.commodityCount2) &&
                    orderResult.docType.code === DocType.ASSEMBLER.code" class="quantity-row">
                    <span v-if="orderResult.commodityCount" class="quantity-item">
                        源商品: {{ formatCount(orderResult.commodityCount.value) }}
                    </span>
                    <span v-if="orderResult.commodityCount2" class="quantity-item">
                        新商品: {{ formatCount(orderResult.commodityCount2.value) }}
                    </span>
                </div>
            </div>

            <!-- Order Affects Categories -->
            <div v-for="category in orderResult?.orderResults" :key="category.category.code"
                class="affect-category-container">
                <hr class="divider" />

                <div class="collapse-container">
                    <div class="collapse-header" @click="toggleCategory(category.category.code)">
                        <span class="category-title" :style="{ color: '#4CA6E6' }">
                            {{ getCategoryTitle(category.category) }}
                        </span>
                        <span class="category-subtitle">{{ category.categorySrcName }}</span>
                        <span class="toggle-icon">{{ openCategories.has(category.category.code) ? '▲' : '▼' }}</span>
                    </div>

                    <div v-show="openCategories.has(category.category.code)" class="collapse-content">
                        <div v-for="(item, index) in category.items" :key="index" class="affect-item">
                            <div class="affect-item-content">
                                <span class="item-title">{{ item.type.name }}:</span>
                                <span class="item-name">{{ item.itemName }}</span>

                                <div class="item-values">
                                    <div class="value-item">
                                        <span v-if="item.count * getDebtFactor(item.type) > 0" class="up-arrow">↑</span>
                                        <span v-if="item.count * getDebtFactor(item.type) < 0"
                                            class="down-arrow">↓</span>
                                        <span class="value-text">
                                            {{ formatItemValue(item.count * getDebtFactor(item.type), item.type) }}
                                        </span>
                                    </div>

                                    <span class="value-text">
                                        共计: {{ formatItemValue(item.countAfter * getDebtFactor(item.type), item.type) }}
                                    </span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Bottom Actions -->
        <template #footer>
            <div class="dialog-footer">
                <el-button v-if="isSupportPreviewAndShare" @click="previewAndShareOrder">
                    分享
                </el-button>

                <el-button type="primary" @click="continuePlaceOrder">
                    继续开单
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script>
import { Util } from '../../public/utils/util';
import { DocType, OrderResultCategoryType, OrderResultCategoryItemType } from '../../public/engine/common/docDefinition';
import { Engine } from '../../public/engine/engine';
import { Inventory, InventoryInOutType } from '../../public/engine/inventory/inventory';
import { uiNavigation } from '../../public/views/uiEntrance/uiNavigation';
import { ipcParam } from '../../public/engine/ipc/ipcParam';
import { OrderResult } from '../../public/engine/common/orderResult';
import { TestSimulateData } from '../../public/engine/testMgr/testSimulateData';
import { AppTheme } from '../../public/theme/appTheme';

export default {
    name: 'OrderResultDialog',
    emits: ['close'],
    data() {
        return {
            dialogVisible: false,
            orderResult: null,
            order: null,
            openCategories: new Set(),
            AppTheme
        }
    },

    computed: {
        DocType() {
            return DocType;
        },

        isSupportPreviewAndShare() {
            const docType = this.orderResult?.docType?.code;
            return [
                DocType.QUOTATION.code, DocType.XSD.code, DocType.XSTHD.code, DocType.CGD.code, DocType.CGTHD.code,
                DocType.RKD.code, DocType.CKD.code
            ].includes(docType);
        },

        isValidOrder() {
            return this.orderResult?.id && this.orderResult.docType.code != DocType.Unknown.code;
        }
    },

    methods: {
        // Open dialog method
        open(orderResult) {
            this.dialogVisible = true;
            this.orderResult = orderResult || ipcParam.getOrderResultParamOne();
            console.log("onLoad order result:" + this.orderResult);
            if (this.orderResult) {
                this.orderResult.resort();

                // Initialize openCategories with all category codes
                this.openCategories = new Set();
                if (this.orderResult.orderResults) {
                    this.orderResult.orderResults.forEach(category => {
                        this.openCategories.add(category.category.code);
                    });
                }
            }
        },

        formatCount(count) {
            return Util.getCountString(count, null);
        },

        formatPrice(price) {
            return Util.getFundString(price);
        },

        getCategoryTitle(categoryType) {
            return OrderResultCategoryType.fromCode(categoryType.code).name;
        },

        formatItemValue(value, itemType) {
            const isFundItem = [
                OrderResultCategoryItemType.FundAccount.code,
                OrderResultCategoryItemType.ReceiveDebt.code,
                OrderResultCategoryItemType.PaymentDebt.code,
                OrderResultCategoryItemType.PreReceiveAccount.code,
                OrderResultCategoryItemType.PrePaymentAccount.code
            ].includes(itemType.code);

            return isFundItem
                ? Util.getFundString(value)
                : Util.getCountString(value, null);
        },

        getDebtFactor(itemType) {
            return itemType.code === 'PaymentDebt' ? -1 : 1;
        },

        handleClose() {
            this.dialogVisible = false;
            this.$emit('close');
        },

        toggleCategory(categoryCode) {
            if (this.openCategories.has(categoryCode)) {
                this.openCategories.delete(categoryCode);
            } else {
                this.openCategories.add(categoryCode);
            }
        },

        showDetail() {
            uiNavigation.showOrderDetailPage({
                docType: this.orderResult.docType,
                id: this.orderResult.id
            });
        },

        async previewAndShareOrder() {
            if (!this.order) {
                switch (this.orderResult.docType.code) {
                    case 'QUOTATION':
                    case 'XSD':
                    case 'XSTHD':
                        // Implement sales order fetching
                        break;

                    case 'CGD':
                    case 'CGTHD':
                        // Implement purchase order fetching
                        break;

                    case 'RKD':
                    case 'CKD':
                        const inventory = await uiNavigation.getInventoryDetail(this.orderResult.id);
                        this.order = inventory;
                        break;

                    default:
                        break;
                }
            }

            if (this.order) {
                uiNavigation.preViewAndShareOrder({
                    order: this.order,
                    fileName: this.order.docType.name
                });
            }
        },

        continuePlaceOrder() {
            switch (this.orderResult.docType.code) {
                case 'QUOTATION':
                    uiNavigation.showSalesQutationDetailPage({ editMode: true });
                    break;

                case 'XSD':
                    uiNavigation.showSalesContractDetailPage({ editMode: true });
                    break;

                case 'XSTHD':
                    uiNavigation.showSalesReturnOrderDetailPage({ editMode: true });
                    break;

                case 'CGD':
                    uiNavigation.showPurchaseContractDetailPage({ editMode: true });
                    break;

                case 'CGTHD':
                    uiNavigation.showPurchaseReturnOrderDetailPage({ editMode: true });
                    break;

                case 'RKD':
                    uiNavigation.showInventoryDetailPage({
                        inventory: Inventory.empty({
                            inOutType: InventoryInOutType.In,
                            operator: Engine.profile?.nickName,
                            operatorId: Engine.profile?.id
                        }),
                        editMode: true
                    });
                    break;

                case 'CKD':
                    uiNavigation.showInventoryDetailPage({
                        inventory: Inventory.empty({
                            inOutType: InventoryInOutType.Out,
                            operator: Engine.profile?.nickName,
                            operatorId: Engine.profile?.id
                        }),
                        editMode: true
                    });
                    break;

                default:
                    break;
            }

            this.handleClose();
        }
    }
}
</script>

<style lang="scss" scoped>
.order-result-dialog {
    display: flex;
    flex-direction: column;
    height: 100%;
    background-color: #ffffff;

    .dialog-content {
        flex: 1;
        overflow-y: auto;
        padding: 15px;
        height: calc(100vh - 120px);
        padding-bottom: 20px;

        .basic-info-container {
            .section-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 5px;

                .order-type {
                    font-size: 18px;
                    font-weight: 500;
                }

                .detail-link {
                    font-size: 14px;
                    color: #666666;
                    cursor: pointer;
                }
            }

            .order-title {
                font-size: 12px;
                color: #999999;
                margin-bottom: 25px;
            }

            .quantity-row {
                display: flex;
                margin-bottom: 15px;
                flex-wrap: wrap;

                .quantity-item {
                    margin-right: 20px;
                    font-size: 14px;
                    margin-bottom: 5px;
                }
            }
        }

        .divider {
            border: none;
            border-top: 1px solid #e0e0e0;
            margin: 15px 0;
        }

        .affect-category-container {
            .collapse-container {
                .collapse-header {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    padding: 10px 0;
                    cursor: pointer;

                    .category-title {
                        font-size: 15px;
                        font-weight: bold;
                    }

                    .category-subtitle {
                        font-size: 13px;
                        color: #666;
                    }

                    .toggle-icon {
                        font-size: 12px;
                    }
                }

                .collapse-content {
                    .affect-item {
                        padding: 10px 0;

                        .affect-item-content {
                            .item-title {
                                font-size: 14px;
                                color: #818181;
                            }

                            .item-name {
                                font-size: 14px;
                                color: #818181;
                                margin-left: 5px;
                            }

                            .item-values {
                                display: flex;
                                margin-top: 5px;
                                flex-wrap: wrap;

                                .value-item {
                                    display: flex;
                                    align-items: center;
                                    width: 120px;
                                    margin-right: 10px;
                                }

                                .up-arrow {
                                    color: #4CAF50;
                                    margin-right: 3px;
                                }

                                .down-arrow {
                                    color: #F44336;
                                    margin-right: 3px;
                                }

                                .value-text {
                                    font-size: 13px;
                                    color: #666666;
                                    width: 200px;
                                    margin-left: 5px;
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    .dialog-footer {
        display: flex;
        justify-content: space-around;
        align-items: center;
        padding: 15px;
        background-color: #ffffff;
        border-top: 1px solid #eeeeee;
        width: 100%;
    }
}
</style>